#!/bin/bash

usage() {
    cat << EOF
USAGE: $0 [ -p <pool> ] <vid>
EOF
}

pool="pool=0"
vid=""
while getopts "p:" OPTION; do
    case "$OPTION" in
	p)
	    pool="pool=$OPTARG"
	    ;;
	h|?)
	    usage
	    exit 1
	    ;;
    esac
done
shift $(($OPTIND - 1))
vid="$1"

if [ -z "$vid" ]; then
    echo "vid not specified"
    exit 1
fi

BINPATH="$(dirname "$0")"
. "$BINPATH/login.inc"

info=0
while read -r line; do
    q="${line%%:*}"
    s="${line#*: *}"
    if [ -z "$q" ]; then
	continue
    fi
    case "$q" in
	mode )
	    info=$((info|1))
	    mode="mode=$s"
	    ;;
	message )
	    info=$((info|2))
	    message="message=$s"
	    ;;
	color )
	    info=$((info|4))
	    color="color=$s"
	    ;;
	playTime )
	    info=$((info|8))
	    playTime="playTime=$s"
	    ;;
	fontsize )
	    info=$((info|16))
	    fontsize="fontsize=$s"
	    ;;
	times )
	    info=$((info|32))
	    date="date=$s"
	    ;;
    esac
    if [ $info == 63 ]; then
	echo post
	eval $curl 'http://bilibili.us/dmpost --data-urlencode "$date" --data-urlencode "$mode" --data-urlencode "$playTime" --data-urlencode "$message" --data-urlencode "$color" --data-urlencode "vid=$vid" --data-urlencode "ms=setDM" --data-urlencode "$pool" --data-urlencode "$fontsize" -e "http://bilibili.us/PADplayer.swf"'
	sleep 5
	info=0
    fi
done
